package gold.digger;

import gold.utils.InputUtil;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC528 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public long totalWeight = 0;
        int length;
        long[][] pos;

        public Solution(int[] w) {
            length = w.length;
            this.pos = new long[w.length][2];
            for (int i = 0; i < w.length; i++) {
                pos[i][0] = totalWeight;
                pos[i][1] = totalWeight + w[i];
                totalWeight = totalWeight + w[i];
            }
        }

        public int pickIndex() {
            long pick = ((long) (Math.random() * totalWeight));
//            System.out.println("-- pick:" + pick);
            int left = 0, right = length - 1, mid = left;
            while (left <= right) {
                mid = left + (right - left) / 2;
                if (pick >= pos[mid][0] && pick < pos[mid][1]) return mid;
                if (pick >= pos[mid][1]) left = mid + 1;
                else right = mid - 1;
            }

            return mid;
        }
    }

    public void run() {
        int[] w = InputUtil.toIntegerArray("[1, 3]");
        Solution solution = new Solution(w);
        for (int i = 0; i < 30; i++) {
            System.out.println(solution.pickIndex());
        }
    }

    public static void main(String[] args) throws Exception {
        LC528 an = new LC528();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
